package com.atguigu.tingshu.album.service.impl;

import com.atguigu.tingshu.album.config.VodConstantProperties;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.util.UploadFileUtil;
import com.atguigu.tingshu.vo.album.TrackMediaInfoVo;
import com.qcloud.vod.VodUploadClient;
import com.qcloud.vod.model.VodUploadRequest;
import com.qcloud.vod.model.VodUploadResponse;
import com.tencentcloudapi.common.AbstractModel;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.vod.v20180717.VodClient;
import com.tencentcloudapi.vod.v20180717.models.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


@Service
@Slf4j
public class VodServiceImpl implements VodService {

    @Autowired
    private VodConstantProperties vodConstantProperties;

    @Autowired
    private VodUploadClient client;

    /**
     * 声音上传
     * @param file
     * @return
     */
    @Override
    public Map<String, String> uploadTrack(MultipartFile file) {
        try {

            String localUrl = UploadFileUtil.uploadTempPath(vodConstantProperties.getTempPath(), file);

            VodUploadRequest request = new VodUploadRequest();
            request.setMediaFilePath(localUrl);
            VodUploadResponse response = client.upload(vodConstantProperties.getRegion(), request);

            if (response != null) {
                Map<String, String> mapResult = new HashMap<>();
                mapResult.put("mediaFileId", response.getFileId());
                mapResult.put("mediaUrl", response.getMediaUrl());
                return mapResult;
            }
        } catch (Exception e) {
            // 业务方进行异常处理
            log.error("Upload Err", e);
        }

        return null;
    }

    @Override
    public TrackMediaInfoVo getTrackMediaInfo(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //3.实例化一个请求对象,每个接口都会对应一个request对象
            DescribeMediaInfosRequest req = new DescribeMediaInfosRequest();
            String[] fileIds1 = {mediaFileId};
            //3.1 封装获取详情对应文件唯一标识
            req.setFileIds(fileIds1);

            //4.调用获取文件详情接口。返回的resp是一个DescribeMediaInfosResponse的实例，与请求对象对应
            DescribeMediaInfosResponse describeMediaInfosResponse = client.DescribeMediaInfos(req);
            //5.解析结果对象获取音频文件时长，大小，类型
            if (describeMediaInfosResponse != null) {
                MediaInfo[] mediaInfoSet = describeMediaInfosResponse.getMediaInfoSet();
                if (mediaInfoSet != null && mediaInfoSet.length > 0) {
                    TrackMediaInfoVo vo = new TrackMediaInfoVo();
                    MediaInfo mediaInfo = mediaInfoSet[0];
                    //5.1 获取媒体文件基本信息对象
                    MediaBasicInfo basicInfo = mediaInfo.getBasicInfo();
                    vo.setType(basicInfo.getType());

                    //5.2 获取媒体文件元信息对象
                    MediaMetaData metaData = mediaInfo.getMetaData();
                    vo.setDuration(metaData.getAudioDuration());
                    vo.setSize(metaData.getSize());
                    return vo;
                }
            }
        } catch (Exception e) {
            log.error("[专辑服务]获取点播平台文件：{}，详情异常：{}", mediaFileId, e);
            throw new GuiguException(400, "音频文件详情获取异常！");
        }
        return null;
    }


    /**
     *  删除声音
     * @param mediaFileId
     */
    @Override
    public void deleteTrackMedia(String mediaFileId) {
        try {
            //1.实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
            Credential cred = new Credential(vodConstantProperties.getSecretId(), vodConstantProperties.getSecretKey());
            //2.实例化一个请求对象,每个接口都会对应一个request对象
            DeleteMediaRequest req = new DeleteMediaRequest();
            req.setFileId(mediaFileId);
            //3.实例化要请求产品的client对象,clientProfile是可选的
            VodClient client = new VodClient(cred, vodConstantProperties.getRegion());
            //4.返回的resp是一个DeleteMediaResponse的实例，与请求对象对应
            client.DeleteMedia(req);
        } catch (TencentCloudSDKException e) {
            log.info("[专辑服务]删除云点播文件：{}，失败{}", mediaFileId, e);
        }
    }

}
